package com.daykw.douyin.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoAuth;
import com.daykw.douyin.model.VideoInfo;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoAuthThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoAuthThread.class);

	private NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
	private SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");

	@Override
	public void run() {

		try {

			List<VideoAuth> auths = dao.query(VideoAuth.class,
					Cnd.where("status", "=", 0).limit(1, 20).desc("follower_num"));

			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			List<Record> cookies = dao.query("t_cookie", Cnd.wrap("WHERE auth_status=1 "));

			headers.put("Host", "dsp.feigua.cn");
			headers.put("Referer", "https://dy.feigua.cn/Member");
			headers.put("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");

			for (VideoAuth task : auths) {
				try {
					int random = org.apache.commons.lang3.RandomUtils.nextInt(0, cookies.size());

					Record cookie = cookies.get(random);
					String cname = cookie.getString("name");
					String c = cookie.getString("cookie");
					headers.put("Cookie", c);
					String html = http.get(task.getAuth_url(), headers);
					if (html.indexOf("参数错误") >= 0) {
						logger.error("参数错误:" + task.getAuth_url());
						dao.update(VideoAuth.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
						continue;
					}

					if (html.equals("302")) {
						logger.info("302," + task.getDataid());
						dao.update("t_cookie", Chain.make("status", 0), Cnd.where("name", "=", cname));
						continue;
					}
					Document doc = Jsoup.parse(html);
					Elements ds = doc.select("div.v-main div.dn-results.icon-search-result");
					if (ds.size() > 0) {
						if (ds.text().indexOf("立即升级会员版本") > 0) {
							dao.update("t_cookie", Chain.make("auth_status", 0), Cnd.where("name", "=", cname));
							// dao.update(VideoAuth.class, Chain.make("status", 5), Cnd.where("id", "=",
							// task.getId()));
							logger.error("##########查询用户详情次数用完，立即升级会员版本");
							return;
						}
					}
					Elements infos = doc.select("div.info li");
					if (!infos.isEmpty()) {
						this.getAuthInfo(doc, task, cookies);

					} else {
						logger.info("用户详情没有内容," + task.getDataid());
						dao.update("t_cookie", Chain.make("status", 0), Cnd.where("name", "=", cname));
					}

				} catch (Exception e) {
					logger.error("", e);
				}

			}

			// System.out.println(ret);

		} catch (Exception e) {

			logger.error("", e);
		}

	}

	public String getAuthExtUserInfo(String kw_uid, List<Record> cookies) {
		try {
			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			int random = org.apache.commons.lang3.RandomUtils.nextInt(0, cookies.size());
			Record cookie = cookies.get(random);
			String cname = cookie.getString("name");
			String c = cookie.getString("cookie");
			headers.put("Cookie", c);
			String html = http.get("https://dy.feigua.cn/Blogger/FansAnalysis?uid=" + kw_uid, headers);

			Document doc = Jsoup.parse(html);

			JSONObject json = new JSONObject();

			JSONArray sexArr = new JSONArray();
			Elements ges = doc.select("div.gender-text div.col-sm-6");
			for (Element s : ges) {
				JSONObject sjson = new JSONObject();
				String val = s.text();
				if (val.indexOf("男") >= 0) {
					String[] sexs = val.split(" ");
					sjson.put("sex", sexs[0]);
					sjson.put("val", sexs[1]);
				} else {
					String[] sexs = val.split(" ");
					sjson.put("sex", sexs[0]);
					sjson.put("val", sexs[1]);
				}
				sexArr.add(sjson);
			}
			json.put("sex", sexArr);

			JSONArray areaArr = new JSONArray();
			Elements trs = doc.select("table.location-table tr");
			for (Element tr : trs) {
				JSONObject ajson = new JSONObject();
				Elements tds = tr.select("td");

				ajson.put("area", tds.get(0).text());
				ajson.put("val", tds.get(1).text());
				areaArr.add(ajson);

			}
			json.put("area", areaArr);

			Elements scripts = doc.getElementsByTag("script");

			String age_data = null;
			for (Element s : scripts) {

				String script = s.toString();
				if (script.indexOf("age_data") > 0) {
					String[] sc = script.split("\r\n");

					for (String row : sc) {
						if (row.indexOf("age_data") > 0) {

							age_data = row.substring(row.indexOf("["), row.lastIndexOf("]") + 1);

							break;
						}

					}

				}
			}

			if (StringUtils.isNotEmpty(age_data)) {
				JSONArray age_data_arry = JSONArray.parseArray(age_data);
				json.put("age_data", age_data_arry);
			} else {
				json.put("age_data", new JSONArray());
			}
			if (json.getJSONArray("age_data").size() > 0 || json.getJSONArray("sex").size() > 0
					|| json.getJSONArray("area").size() > 0) {
				return json.toJSONString();
			} else {
				logger.info("kw_uid:" + kw_uid + "获取其他信息为空");
				return null;
			}

		} catch (Exception e) {
			logger.error("", e);
			return null;
		}

	}

	public String getAuthExtFansInfo(Document doc) {
		JSONObject json = new JSONObject();
		Elements scripts = doc.getElementsByTag("script");
		String fans30 = null;
		String fans90 = null;
		String fansInc30 = null;
		String fansInc90 = null;
		String age_data = null;
		for (Element s : scripts) {

			String script = s.toString();
			if (script.indexOf("fans30") > 0) {
				String[] sc = script.split("\r\n");

				for (String row : sc) {
					if (row.indexOf("fans30") > 0) {
						// var url = '/Aweme/GetComment?uid=63625792717' +
						// '&awemeId=6678156513263111432' + '&page=1';
						fans30 = row.substring(row.indexOf("["), row.lastIndexOf("]") + 1);

						break;
					}

				}

			}

			if (script.indexOf("fans90") > 0) {
				String[] sc = script.split("\r\n");

				for (String row : sc) {
					if (row.indexOf("fans90") > 0) {
						// var url = '/Aweme/GetComment?uid=63625792717' +
						// '&awemeId=6678156513263111432' + '&page=1';
						fans90 = row.substring(row.indexOf("["), row.lastIndexOf("]") + 1);

						break;
					}

				}

			}

			if (script.indexOf("fansInc30") > 0) {
				String[] sc = script.split("\r\n");

				for (String row : sc) {
					if (row.indexOf("fansInc30") > 0) {
						// var url = '/Aweme/GetComment?uid=63625792717' +
						// '&awemeId=6678156513263111432' + '&page=1';
						fansInc30 = row.substring(row.indexOf("["), row.lastIndexOf("]") + 1);

						break;
					}

				}

			}

			if (script.indexOf("fansInc90") > 0) {
				String[] sc = script.split("\r\n");

				for (String row : sc) {
					if (row.indexOf("fansInc90") > 0) {
						// var url = '/Aweme/GetComment?uid=63625792717' +
						// '&awemeId=6678156513263111432' + '&page=1';
						fansInc90 = row.substring(row.indexOf("["), row.lastIndexOf("]") + 1);

						break;
					}

				}

			}

		}

		if (StringUtils.isNotEmpty(fans30)) {
			JSONArray fans30_arry = JSONArray.parseArray(fans30);
			json.put("fans30", fans30_arry);
		} else {
			json.put("fans30", new JSONArray());
		}

		if (StringUtils.isNotEmpty(fans90)) {
			JSONArray fans90_arry = JSONArray.parseArray(fans90);
			json.put("fans90", fans90_arry);
		} else {
			json.put("fans90", new JSONArray());
		}

		if (StringUtils.isNotEmpty(fansInc30)) {
			JSONArray fansInc30_arry = JSONArray.parseArray(fansInc30);
			json.put("fansInc30", fansInc30_arry);
		} else {
			json.put("fansInc30", new JSONArray());
		}

		if (StringUtils.isNotEmpty(fansInc90)) {
			JSONArray fansInc90_arry = JSONArray.parseArray(fansInc90);
			json.put("fansInc90", fansInc90_arry);
		} else {
			json.put("fansInc90", new JSONArray());
		}

		if (StringUtils.isNotEmpty(age_data)) {
			JSONArray age_data_arry = JSONArray.parseArray(age_data);
			json.put("age_data", age_data_arry);
		} else {
			json.put("age_data", new JSONArray());
		}

		return json.toJSONString();
	}

	public void getAuthInfo(Document doc, VideoAuth task, List<Record> cookies) {
		try {

			Elements infos = doc.select("div.info li");

			String nickname = doc.select("div.info div.nickname").text();

			nickname = nickname.replace(" 已开通商品橱窗", "");

			// String[] ns = nickname.split(" ");
			String avatar = doc.select("div.avatar img").first().attr("src");

			String kw_user_cate = null;
			String douyinid = null;
			String sex = null;
			Integer age = null;
			String local = null;
			for (Element info : infos) {
				String title = info.ownText();
				Elements sss = info.select("span");

				if (title.indexOf("抖音号") >= 0) {
					douyinid = info.select("span").text();
				}
				if (title.indexOf("分类") >= 0) {

					if (sss.size() > 1) {
						kw_user_cate = sss.get(1).text();
					} else {
						kw_user_cate = sss.get(0).text();
					}
				}
				if (title.indexOf("性别") >= 0) {

					sex = sss.get(0).text();

				}
				if (title.indexOf("年龄") >= 0) {

					String nl = sss.get(0).text();
					age = Integer.parseInt(nl.trim());
				}
				if (title.indexOf("地区") >= 0) {

					if (sss.size() > 1) {
						local = sss.get(1).text();
					} else {
						local = sss.get(0).text();
					}

				}
			}

			Elements scripts = doc.getElementsByTag("script");
			String uid = null;
			String mcnid = null;
			for (Element s : scripts) {

				String script = s.toString();
				if (script.indexOf("bloggerId") > 0) {
					String[] rows = script.split("\r\n");
					for (String row : rows) {
						if (row.indexOf("bloggerId") > 0) {
							uid = row.substring(row.indexOf("'") + 1, row.lastIndexOf("'"));
							break;
						}

					}

				}
			}

			for (Element s : scripts) {

				String script = s.toString();
				if (script.indexOf("mcnid") > 0) {
					String[] rows = script.split("\r\n");
					for (String row : rows) {
						if (row.indexOf("mcnid ") > 0) {
							mcnid = row.substring(row.indexOf("'") + 1, row.lastIndexOf("'"));
							break;
						}

					}

				}
			}
			String intro = doc.select("div.intro").text();
			Integer follower_num = 0;
			Integer status_num = 0;
			Integer like_num = 0;
			Integer share_num = 0;
			Integer avg_cmt_num = 0;
			Integer avg_share_num = 0;
			Integer avg_like_num = 0;
			Integer follower_add_30 = 0;
			Integer video_add_90 = 0;
			Elements col3 = doc.select("div.owner-data div.row.col3 div.col-sm-4");
			for (Element col : col3) {
				String title = col.text();
				if (title.indexOf("粉丝数") >= 0) {
					String val = col.select("span").text();

					follower_num = getInt(val);
				} else if (title.indexOf("作品数") >= 0) {
					String val = col.select("span").text();

					status_num = getInt(val);

				}
			}
			Elements col2 = doc.select("div.owner-data div.row.col2 div.col-sm-6");
			for (Element col : col2) {
				String title = col.ownText();
				String val = col.select("span").text();
				if (title.indexOf("总点赞") >= 0) {

					like_num = getInt(val);
				} else if (title.indexOf("平均点赞") >= 0) {
					avg_like_num = getInt(val);
				} else if (title.indexOf("总评论") >= 0) {

				} else if (title.indexOf("平均评论") >= 0) {
					avg_cmt_num = getInt(val);
				} else if (title.indexOf("总分享") >= 0) {
					share_num = getInt(val);
				} else if (title.indexOf("平均分享") >= 0) {
					avg_share_num = getInt(val);
				} else if (title.indexOf("近30天粉丝增量") >= 0) {
					follower_add_30 = getInt(val);
				} else if (title.indexOf("近90天视频发布") >= 0) {
					video_add_90 = Integer.parseInt(val.replace("个", ""));
				}

			}
			if (StringUtils.isNotEmpty(intro)) {
				intro = intro.replace("简介：", "");
			}
			task.setUser_description(intro);
			task.setKw_profileImageUrl(avatar);
			// task.setKw_nick_name(ns[0]);
			if (StringUtils.isEmpty(task.getKw_uid())) {
				task.setKw_uid(uid);
				task.setKw_user_url("https://www.iesdouyin.com/share/user/" + uid);
			}

			if (StringUtils.isNotEmpty(task.getKw_uid())) {
				dao.update(VideoInfo.class, Chain.make("kw_uid", task.getKw_uid()),
						Cnd.where("dataid", "=", task.getDataid()));
			}

			task.setMcnid(mcnid);
			task.setKw_douyin_id(douyinid);
			task.setDate_age(age);
			task.setKw_nick_name(nickname);
			task.setKw_user_cate(kw_user_cate);
			task.setUser_gender(sex);
			task.setFollower_num(follower_num);
			task.setStatus_num(status_num);
			task.setShare_num(share_num);
			task.setLike_num(like_num);
			task.setAvg_cmt_num(avg_cmt_num);
			task.setAvg_like_num(avg_like_num);
			task.setAvg_share_num(avg_share_num);
			task.setFollower_add_30(follower_add_30);
			task.setVideo_add_90(video_add_90);
			task.setLocation(local);
			task.setSource_name("douyin.com");
			task.setUdate(Long.parseLong(fmt.format(new Date())));
			task.setStatus(2);
			dao.update(task);

			String ext_info = this.getAuthExtFansInfo(doc);
			if (StringUtils.isNotEmpty(ext_info)) {
				dao.update(VideoAuth.class, Chain.make("ext_info", ext_info), Cnd.where("id", "=", task.getId()));
			}
			String ext_user = this.getAuthExtUserInfo(task.getKw_uid(), cookies);
			if (StringUtils.isNotEmpty(ext_user)) {
				dao.update(VideoAuth.class, Chain.make("ext_user", ext_user),
						Cnd.where("kw_uid", "=", task.getKw_uid()));
			}

			logger.info("用户详情" + nickname + "下载完毕");
			Thread.sleep(5000);

		} catch (Exception e) {
			logger.error("", e);
		}
	}

	private Integer getInt(String val) {
		try {
			if (val.equals("--")) {
				return 0;
			}
			if (val.equals("-")) {
				return 0;
			}
			if (val.indexOf("亿") > 0) {
				val = val.replace("亿", "0000000");
			}
			if (val.indexOf("w") > 0) {
				val = val.replace("w", "000");
			}
			if (val.indexOf(".") > 0) {
				val = val.replace(".", "");
			}
			return Integer.parseInt(val);
		} catch (Exception e) {
			logger.error("", e);
			return 0;
		}

	}
}
